/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.cx1.web.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang.StringUtils;
import org.cx1.model.Listing;
import org.cx1.model.utils.ServiceResponse;
import org.cx1.model.User;
import org.cx1.model.utils.SystemProperties;
import org.cx1.service.api.IEmailService;
import org.cx1.service.api.IListingService;
import org.cx1.service.api.IUserService;
import org.cx1.service.impl.DListingService;
import org.cx1.service.impl.DUserService;
import org.cx1.service.impl.MEmailService;
import org.cx1.service.impl.MListingService;
import org.cx1.service.impl.MUserService;
import org.cx1.web.controller.action.UserAction;
import org.cx1.web.utils.SessionUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
import org.springframework.web.servlet.view.RedirectView;

/**
 *
 * @author ECH
 */
public class UserController extends BaseController {
    
    //private IUserService userService = new MUserService();
    //private IListingService listingService = new MListingService();
    
    private IUserService userService = new DUserService();
    private IListingService listingService = new DListingService();
    private IEmailService emailService = new MEmailService();
    
    public UserController() {
        
    }
    
    protected ModelAndView handleRequestInternal( HttpServletRequest request,
                                                  HttpServletResponse response) throws Exception {
        ModelAndView mav = new ModelAndView();
        Map map = new HashMap();        
        
        boolean loggedin = false;
        String userID = SessionUtils.getUserID(request.getSession());   
        
        if (!StringUtils.isEmpty(userID)) {
            loggedin = true;
            map.put("loggedin", loggedin);
        }
        
        Map<String, Object> parameterMap = new HashMap<String, Object>();
        if (ServletFileUpload.isMultipartContent(request)) {
            parameterMap = this.getMultipartFormParams(request);
        } 
        else {
            parameterMap = this.getFormParams(request);
        }
        
        Map<String, String> formfields = (Map<String, String>) parameterMap.get("formfields");
        int action = StringUtils.isEmpty(formfields.get("a")) ? 0 : Integer.parseInt(formfields.get("a"));
        
        switch (action) {
            case UserAction.READ_ALL: {                      
                if (loggedin) {
                    readAll(mav, map, request);            
                }
                else {
                    mav.setView(new RedirectView("home.htm"));
                    return mav;                    
                }
                break;
            }
            case UserAction.READ: {                      
                if (loggedin) {
                    read(mav, map, request);          
                }
                else {
                    mav.setView(new RedirectView("home.htm"));
                    return mav;                    
                }
                break;
            }
            case UserAction.CREATE: {                      
                if (loggedin) {
                    create(mav, map, request);            
                }
                else {
                    mav.setView(new RedirectView("home.htm"));
                    return mav;                    
                }
                break;
            }
            case UserAction.UPDATE: {                      
                if (loggedin) {
                    update(mav, map, request);          
                }
                else {
                    mav.setView(new RedirectView("home.htm"));
                    return mav;                    
                }
                break;
            }    
            case UserAction.DELETE: {                      
                if (loggedin) {
                    delete(mav, map, request);            
                }
                else {
                    mav.setView(new RedirectView("home.htm"));
                    return mav;                    
                }
                break;
            }
            default: {                      
                if (loggedin) {
                    mav.setView(new RedirectView("home.htm"));
                }
                else {
                    mav.setView(new RedirectView("home.htm"));
                    return mav;                    
                }
                break;
            }
        }  
        
        map.put("host", SystemProperties.SYSTEM_HOST);
        map.put("port", SystemProperties.SYSTEM_PORT);
        map.put("props", this.getSystemProperties());
        mav.addObject("model", map);
        return mav;
    }
    
    private void readAll(ModelAndView mav, Map map, HttpServletRequest request) {String offset = request.getParameter("offset");
        String limit = request.getParameter("limit");
        ServiceResponse<List<User>> response = userService.readAll(StringUtils.isEmpty(offset) ? 0 : Integer.parseInt(offset), StringUtils.isEmpty(limit) ? 0 : Integer.parseInt(limit));        
        map.put("users", response.getResponse());
        mav.setViewName("users");
    }
    
    private void read(ModelAndView mav, Map map, HttpServletRequest request) {
        String userID = request.getParameter("id");
        ServiceResponse<User> response1 = this.userService.read(userID);
        ServiceResponse<List<Listing>> response2 = listingService.readUserListings(userID, 0, 0);
        map.put("user", response1.getResponse());
        map.put("listings", response2.getResponse());
    }
    
    private void create(ModelAndView mav, Map map, HttpServletRequest request) {
        if (!StringUtils.isEmpty(request.getParameter("s"))) {
                        
            String userTypeID = request.getParameter("userTypeID");
            
            String brokerID = request.getParameter("brokerID");
            String gmailID = request.getParameter("gmailID");
            String yahooID = request.getParameter("yahooID");
            String facebookID = request.getParameter("facebookID");
            
            String email = request.getParameter("email");
            String password = request.getParameter("password");
                
            String name = request.getParameter("name");
            String firstName = StringUtils.isEmpty(request.getParameter("firstName")) ? "" : request.getParameter("firstName");
            String lastName = StringUtils.isEmpty(request.getParameter("lastName")) ? "" : request.getParameter("lastName");
                
            String title = request.getParameter("title");            
            String description = request.getParameter("description");            
            String notes = request.getParameter("notes");
            
            String emailPrimary = request.getParameter("emailPrimary");
            String emailSecondary = request.getParameter("emailSecondary");
            
            String landlinePrimary = request.getParameter("landlinePrimary");
            String landlineSecondary = request.getParameter("landlineSecondary");
            
            String mobilePrimary = request.getParameter("mobilePrimary");
            String mobileSecondary = request.getParameter("mobileSecondary");
                        
            String primaryPhotoID = request.getParameter("primaryPhotoID");            
            String photoIDs = request.getParameter("photoIDs");        
            
            String contactIDs = request.getParameter("contactIDs");            
            String companyIDs = request.getParameter("companyIDs");
                       
            User user = new User();
            user.setUserTypeID(userTypeID);
            
            user.setBrokerID(brokerID);
            user.setGmailID(gmailID);
            user.setYahooID(yahooID);
            user.setFacebookID(facebookID);
            
            user.setEmail(email);
            user.setPassword(password);
            
            user.setFirstName(firstName);
            user.setLastName(lastName);
            user.setName(name);
            
            user.setTitle(title);
            user.setDescription(description);
            user.setNotes(notes);
            
            user.setEmailPrimary(emailPrimary);
            user.setEmailSecondary(emailSecondary);
            
            user.setLandlinePrimary(landlinePrimary);
            user.setLandlineSecondary(landlineSecondary);
            
            user.setMobilePrimary(mobilePrimary);
            user.setMobileSecondary(mobileSecondary);
            
            user.setPrimaryPhotoID(primaryPhotoID);
            user.setPhotoIDs(StringUtils.isEmpty(photoIDs) ? null : Arrays.asList(photoIDs.split("\\s*,\\s*")));
            
            user.setContactIDs(StringUtils.isEmpty(contactIDs) ? null : Arrays.asList(contactIDs.split("\\s*,\\s*")));
            user.setCompanyIDs(StringUtils.isEmpty(companyIDs) ? null : Arrays.asList(companyIDs.split("\\s*,\\s*")));

            ServiceResponse<String> response = userService.create(user);
            
            if (response.isSuccessful() && !StringUtils.isEmpty(response.getResponse())) {
                emailService.sendSignupConfirmation(firstName, email, password);
            }
            
            map.put("user", response.getResponse());
            mav.setView(new RedirectView("user.htm?a="+UserAction.READ+"&id="+response.getResponse()));   
        }
        else {
            mav.setViewName("useradd");
        }
    }
    
    private void update(ModelAndView mav, Map map, HttpServletRequest request) {
        if (!StringUtils.isEmpty(request.getParameter("s"))) {             
            String id = request.getParameter("id");    
            String userTypeID = request.getParameter("userTypeID");
            
            String brokerID = request.getParameter("brokerID");
            String gmailID = request.getParameter("gmailID");
            String yahooID = request.getParameter("yahooID");
            String facebookID = request.getParameter("facebookID");
            
            String email = request.getParameter("email");
            String password = request.getParameter("password");
                
            String firstName = StringUtils.isEmpty(request.getParameter("firstName")) ? "" : request.getParameter("firstName");
            String lastName = StringUtils.isEmpty(request.getParameter("lastName")) ? "" : request.getParameter("lastName");
                
            String name = request.getParameter("name");
                
            String title = request.getParameter("title");            
            String description = request.getParameter("description");            
            String notes = request.getParameter("notes");
            
            String emailPrimary = request.getParameter("emailPrimary");
            String emailSecondary = request.getParameter("emailSecondary");
            
            String landlinePrimary = request.getParameter("landlinePrimary");
            String landlineSecondary = request.getParameter("landlineSecondary");
            
            String mobilePrimary = request.getParameter("mobilePrimary");
            String mobileSecondary = request.getParameter("mobileSecondary");
            
            String primaryPhotoID = request.getParameter("primaryPhotoID");            
            String photoIDs = request.getParameter("photoIDs");        
            
            String contactIDs = request.getParameter("contactIDs");            
            String companyIDs = request.getParameter("companyIDs");
                        
            ServiceResponse<User> response1 = userService.read(id);              
            User user = response1.getResponse();          

            if (user != null) {
                user.setUserTypeID(userTypeID);
            
                user.setBrokerID(brokerID);
                user.setGmailID(gmailID);
                user.setYahooID(yahooID);
                user.setFacebookID(facebookID);

                user.setEmail(email);
                user.setPassword(password);

                user.setFirstName(firstName);
                user.setLastName(lastName);
                
                user.setName(name);

                user.setTitle(title);
                user.setDescription(description);
                user.setNotes(notes);

                user.setEmailPrimary(emailPrimary);
                user.setEmailSecondary(emailSecondary);

                user.setLandlinePrimary(landlinePrimary);
                user.setLandlineSecondary(landlineSecondary);

                user.setMobilePrimary(mobilePrimary);
                user.setMobileSecondary(mobileSecondary);
            
                user.setPrimaryPhotoID(primaryPhotoID);
                user.setPhotoIDs(StringUtils.isEmpty(photoIDs) ? null : Arrays.asList(photoIDs.split("\\s*,\\s*")));

                user.setContactIDs(StringUtils.isEmpty(contactIDs) ? null : Arrays.asList(contactIDs.split("\\s*,\\s*")));
                user.setCompanyIDs(StringUtils.isEmpty(companyIDs) ? null : Arrays.asList(companyIDs.split("\\s*,\\s*")));
                
                ServiceResponse<Boolean> response = userService.update(user);
                map.put("user", response.getResponse());
                mav.setView(new RedirectView("user.htm?a="+UserAction.READ+"&id="+id));
            }
            else {
                mav.setView(new RedirectView("user.htm"));                
            }
            
            ServiceResponse<Boolean> response = userService.update(user);
            map.put("user", response.getResponse());
            mav.setView(new RedirectView("user.htm?a="+UserAction.READ+"&id="+id));
        }        
        else {                  
            String id = request.getParameter("id");    
            ServiceResponse<User> response = userService.read(id);
            map.put("user", response.getResponse());
            mav.setViewName("useredit");
        }
    }
    
    private void delete(ModelAndView mav, Map map, HttpServletRequest request) {
        String id = request.getParameter("id");
        ServiceResponse<Boolean> response = userService.delete(id);        
        mav.setView(new RedirectView("user.htm?a="+UserAction.READ_ALL));
    }
    
    /*
    private void getUserAll(ModelAndView mav, Map map, HttpServletRequest request) {
        ServiceResponse<List<User>> response = userService.getUserAll();
        map.put("users", response.getResponse());
        mav.setViewName("userall");
    }
        
    private void getUser(ModelAndView mav, Map map, HttpServletRequest request) {
        String id = request.getParameter("id");
        ServiceResponse<User> response = userService.getUser(id);
        ServiceResponse<List<Listing>> response1 = postingService.getUserPostings(id);
        map.put("user", response.getResponse());
        map.put("postings", response1.getResponse());
        mav.setViewName("user");
    }
    
    private void createUser(ModelAndView mav, Map map, HttpServletRequest request, Map parameterMap) {
        
        try {
            
            Map<String, String> formfields = (Map<String, String>) parameterMap.get("formfields");
            List<String> images = new ArrayList<String>();

            boolean isMultipart = ServletFileUpload.isMultipartContent(request);

            if (isMultipart) {
                List filefields = (List) parameterMap.get("filefields");
                Iterator iterator = filefields.iterator();

                while (iterator.hasNext()) {
                    FileItem item = (FileItem) iterator.next();

                    if (!item.isFormField()) {
                        String fileName = item.getName();

                        if (!StringUtils.isEmpty(fileName)) {
                            String root = getServletContext().getRealPath("/");
                            root = "D:/CX1/uploads/img";
                            File path = new File(root);
                            if (!path.exists()) {
                                boolean status = path.mkdirs();
                            }

                            File uploadedFile = new File(path + "/" + fileName);
                            if (!uploadedFile.exists()) {
                                System.out.println(uploadedFile.getAbsolutePath());
                                item.write(uploadedFile);
                            }

                            images.add(fileName);
                        }
                    }
                }
            }

            if (formfields != null && !StringUtils.isEmpty((String) formfields.get("s"))) {

                String name = (String) formfields.get("name");
                String uname = (String) formfields.get("uname");
                String email = (String) formfields.get("email");
                String pass = (String) formfields.get("pass");
                String prof = (String) formfields.get("prof");

                ServiceResponse<String> response = userService.addUser(name, prof, uname, email, pass, images);
                mav.setView( new RedirectView("user.htm?a=" + UserAction.VIEW_ALL) );
            } 
            else {
                mav.setViewName("useradd");
            }
        } 
        catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    
    private void deactivateUser(ModelAndView mav, Map map, HttpServletRequest request) {
        String id = request.getParameter("id");
        ServiceResponse<Boolean> response = userService.deactivateUser(id);
        mav.setView(new RedirectView("user.htm"));
    }
    
    private void updateUser(ModelAndView mav, Map map, HttpServletRequest request) {
        if (!StringUtils.isEmpty(request.getParameter("s"))) {
            String id = request.getParameter("id");

            String name = request.getParameter("name");
            String uname = request.getParameter("uname");
            String email = request.getParameter("email");
            String pass = request.getParameter("pass");
            String prof = request.getParameter("prof");

            ServiceResponse<String> response = userService.updateUser(id, name, prof, uname, email, pass);
            mav.setView(new RedirectView("user.htm?a=2&id="+id));
        } 
        else {
            String id = request.getParameter("id");

            ServiceResponse<User> response = userService.getUser(id);
            map.put("user", response.getResponse());

            mav.setViewName("userupdate");
        }
    }
    
    
    private void addImage(ModelAndView mav, Map map, HttpServletRequest request, Map parameterMap) {        
        Map<String, String> formfields = (Map<String, String>) parameterMap.get("formfields");
        List<String> images = new ArrayList<String>();
        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        
        try {
            if (isMultipart) {
                List filefields = (List) parameterMap.get("filefields");
                Iterator iterator = filefields.iterator();

                while (iterator.hasNext()) {
                    FileItem item = (FileItem) iterator.next();

                    if (!item.isFormField()) {
                        String fileName = item.getName();

                        if (!StringUtils.isEmpty(fileName)) {
                            String root = getServletContext().getRealPath("/");
                            root = "D:/CX1/uploads/img";
                            File path = new File(root);

                            if (!path.exists()) {
                                boolean status = path.mkdirs();
                            }

                            File uploadedFile = new File(path + "/" + fileName);
                            if (!uploadedFile.exists()) {
                                System.out.println(uploadedFile.getAbsolutePath());
                                item.write(uploadedFile);
                            }

                            images.add(fileName);
                        }
                    }
                }
            }

            if (formfields != null && !StringUtils.isEmpty((String) formfields.get("s"))) {
                String id = formfields.get("id");
                ServiceResponse<String> response = userService.addUserImages(id, images);
            }            
        } 
        catch (Exception ex) {
            ex.printStackTrace();
        }
        
        mav.setView(new RedirectView("user.htm"));
    }
        
    private void removeImage(ModelAndView mav, Map map, HttpServletRequest request, Map parameterMap) {
        String userID = request.getParameter("pid");
        String imageID = request.getParameter("iid");
        ServiceResponse<Boolean> response = userService.removeUserImage(userID, imageID);
    }
    */
}
